package org.modelcc.io.java.processor;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.modelcc.io.java.JavaLanguageClass;
import org.modelcc.io.java.JavaModelProcessor;
import org.modelcc.io.java.JavaModelReader;
import org.modelcc.io.java.JavaLanguageMetadata;

/**
 * Convert priority values into precedence relationships
 */
public class PriorityToPrecedenceConverter extends JavaModelProcessor<JavaLanguageMetadata>
{	
	public PriorityToPrecedenceConverter (JavaModelReader reader)
	{
		super(reader);
	}
	
	@Override
	public void process(JavaLanguageMetadata metadata) 
	{
		Set<JavaLanguageClass> elements = metadata.getJavaElements();
		Map<JavaLanguageClass,Integer> priorities = metadata.prePriorities;
		Map<JavaLanguageClass,Set<JavaLanguageClass>> precedences = metadata.prePrecedences;

    	JavaLanguageClass el;
    	JavaLanguageClass el2;
    	
    	for (Iterator<JavaLanguageClass> it1 = elements.iterator();it1.hasNext();) {
    		el = it1.next();
    		Integer prio = priorities.get(el);
    		if (prio != null) {
    			for (Iterator<JavaLanguageClass> it2 = elements.iterator();it2.hasNext();) {
    				el2 = it2.next();
    				Integer prio2 = priorities.get(el2);
    				if (prio2 != null) {
    					if (prio < prio2) {
    						Set<JavaLanguageClass> se = precedences.get(el);
    						if (se == null) {
    							se = new HashSet<JavaLanguageClass>();
    							precedences.put(el,se);
    						}
    						se.add(el2);
    					}
    					else if (prio2 < prio) {
    						Set<JavaLanguageClass> se = precedences.get(el2);
    						if (se == null) {
    							se = new HashSet<JavaLanguageClass>();
    							precedences.put(el2,se);
    						}
    						se.add(el);
    					}
    				}
    			}
    		}
    	}		
    }
}
